package com.ym.controller.doctor.contacts;

import com.ym.common.constant.Coder;
import com.ym.common.constant.Constants;
import com.ym.core.domain.APIResponse;
import com.ym.core.domain.BaseController;
import com.ym.core.rabbit.IMessageSenderSV;
import com.ym.core.rabbit.MessageTypeEnum;
import com.ym.core.rabbit.NormalMessageTask;
import com.ym.core.utils.yunxin.YunXinApiUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * 通讯录患者相关接口
 *
 * @author: 李涛
 * @version: 2019年05月22日 10:23
 */
@Api(tags = "医生端-通讯录-聊天相关")
@RestController
@RequestMapping(value = "/doctor/contacts/chat",headers = Constants.Api.VERSION)
@Validated
public class ContactsChatController extends BaseController {

	public static final Logger logger = LoggerFactory.getLogger(ContactsChatController.class);

	@Autowired
	private IMessageSenderSV messageSenderSV;


	@ApiOperation(value = "网易云消息抄送接口")
	@PostMapping("/sync/messages")
	public APIResponse syncChatMessages(
			@RequestHeader String AppKey,
			@RequestHeader String CurTime,
			@RequestHeader String CheckSum,
			@RequestHeader String MD5,
			HttpServletRequest req
	) {
		APIResponse rsp = APIResponse.success();
		// 获取请求体
		String contentType = req.getContentType();
		try {
			byte[] body = readBody(req);
			// 将请求体转成String格式，并打印
			String requestBody = new String(body, "utf-8");
			// 获取计算过的md5及checkSum
			String verifyMD5 = YunXinApiUtil.CheckSumBuilder.getMD5(requestBody);
			String verifyChecksum = YunXinApiUtil.CheckSumBuilder.getCheckSum(YunXinApiUtil.yunxinConfig.getSecret(), verifyMD5, CurTime);
			//比较md5、checkSum是否一致.一致表示数据正常
			if (verifyChecksum.equals(CheckSum) && verifyMD5.equals(MD5)) {
				//处理业务
				messageSenderSV.sendMsg(new NormalMessageTask(MessageTypeEnum.YUN_XIN, requestBody));
			}
		} catch (Exception ex) {
			logger.error(ex.getMessage(), ex);
			rsp = APIResponse.fail(Coder.System.YUNXIN_FAIL);
		}
		return rsp;
	}

	/**
	 * 读取request的body体
	 *
	 * @param request
	 * @return
	 * @throws IOException
	 */
	private byte[] readBody(HttpServletRequest request) throws IOException {
		if (request.getContentLength() > 0) {
			byte[] body = new byte[request.getContentLength()];
			IOUtils.readFully(request.getInputStream(), body);
			return body;
		}
		return null;
	}


}
